<template>
	<view>
		<view class="uni-header">
			<view class="uni-group">
				<view class="uni-title"></view>
				<view class="uni-sub-title"></view>
			</view>
			<view class="uni-group">
				<input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
				<button class="uni-button" type="default" size="mini" @click="search">搜索</button>
				<button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
				<button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length"
					@click="delTable">批量删除</button>
			</view>
		</view>
		<view class="uni-container">
			<uni-table border stripe type="selection" @selection-change="selectionChange">
				<uni-tr>
					<uni-th align="">名称</uni-th>
					<uni-th align="center">图标</uni-th>
					<uni-th align="center">排序</uni-th>
					<uni-th align="center">类别描述</uni-th>
					<uni-th align="center">加入热门</uni-th>
					<uni-th align="center">首页显示</uni-th>
					<uni-th align="center">生效状态</uni-th>
					<uni-th align="center">create_date</uni-th>
					<uni-th width="204" align="center">操作</uni-th>
				</uni-tr>
				<uni-tr v-for="(item,index) in dataList" :key="index">
					<uni-td align=""> {{item.name}} </uni-td>
					<uni-td align="center">
						<image v-if="item.icon" :src="item.icon" mode="aspectFill" class="image-width-80 border-radius">
						</image>
					</uni-td>
					<uni-td align="center"> {{item.sort}} </uni-td>
					<uni-td align="center"> {{item.description}} </uni-td>
					<uni-td align="center"> {{item.is_hot_show == true ? '✅' : '❌'}} </uni-td>
					<uni-td align="center"> {{item.is_index_show == true ? '✅' : '❌'}} </uni-td>
					<uni-td align="center"> {{item.status == true ? '✅' : '❌'}} </uni-td>
					<uni-td align="center">
						<uni-dateformat :date="item.create_date" :threshold="[0, 0]" />
					</uni-td>
					<uni-td align="center">
						<view class="uni-group">
							<button v-if="!item.parent_id" @click="navigateTo('./add?pid='+item._id, false)"
								class="uni-button" size="mini" type="primary">子分类</button>
							<button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini"
								type="primary">修改</button>
							<button @click="confirmDelete(item._id)" class="uni-button" size="mini"
								type="warn">删除</button>
						</view>
					</uni-td>
				</uni-tr>
			</uni-table>
		</view>
	</view>
</template>

<script>
	import {
		enumConverter
	} from '../../js_sdk/validator/opendb-mall-categories.js';

	const db = uniCloud.database()
	// 表查询配置
	const dbOrderBy = '' // 排序字段
	const dbSearchFields = ["name", "description"] // 模糊搜索字段，支持模糊搜索的字段列表
	// 分页配置
	const pageSize = 20
	const pageCurrent = 1
	// 菜单扁平化
	function flatMenu(menu, result, depth = 0) {
		menu.name = (depth ? '　'.repeat(depth) + '|-' : '') + menu.name
		result.push(menu)
		if (menu.children) {
			flatMenus(menu.children, result, depth + 1)
		}
	}

	function flatMenus(menus, result = [], depth = 0) {
		menus.forEach(menu => flatMenu(menu, result, depth))
		return result
	}
	export default {
		data() {
			return {
				dataList: [],
				query: '',
				where: '',
				orderby: dbOrderBy,
				selectedIndexs: [],
				options: {
					pageSize,
					pageCurrent,
					...enumConverter
				},
				imageStyles: {
					width: 64,
					height: 64
				}
			}
		},
		onLoad() {
			this.search()
		},
		methods: {
			getWhere() {
				const query = this.query.trim()
				if (!query) {
					return;
				}
				const queryRe = new RegExp(query, 'i')
				return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
			},
			search() {
				const newWhere = this.getWhere()
				this.where = newWhere
				this.loadData(newWhere)
			},
			loadData(newWhere) {
				let collection = db.collection("opendb-mall-categories")
				if (newWhere) {
					collection.where(newWhere);
				}
				collection.field(
					"parent_id,name,icon,sort,description,is_hot_show,is_index_show,status,create_date").orderBy(
					"sort asc").limit(50).get({
					getTree: true
				}).then(({
					result
				}) => {
					this.dataList = flatMenus(result.data);
				})
			},
			onPageChanged(e) {
				this.$refs.udb.loadData({
					current: e.current
				})
			},
			navigateTo(url, clear) {
				// clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
				uni.navigateTo({
					url,
					events: {
						refreshData: () => {
							this.loadData(clear)
						}
					}
				})
			},
			// 多选处理
			selectedItems() {
				var dataList = this.$refs.udb.dataList
				return this.selectedIndexs.map(i => dataList[i]._id)
			},
			// 批量删除
			delTable() {
				let ids = this.selectedItems().join(",");
				uni.showModal({
					content: "是否确定删除？",
					success: (res) => {
						if (res.confirm) {
							db.collection("opendb-mall-categories").where(`_id in([${ids}])`).remove().then(
								() => {
									uni.showToast({
										icon: "success",
										title: "删除成功"
									})
									this.search()
								});
						}
					}
				})

			},
			// 多选
			selectionChange(e) {
				this.selectedIndexs = e.detail.index
			},
			confirmDelete(id) {
				uni.showModal({
					content: "是否确定删除？",
					success: (res) => {
						if (res.confirm) {
							db.collection("opendb-mall-categories").doc(id).remove().then(() => {
								uni.showToast({
									icon: "success",
									title: "删除成功"
								})
								this.search()
							});
						}
					}
				})
			}
		}
	}
</script>
<style>
</style>
